<?php

class Images_Model_Upload {
	
	static function upload($path,$extensions, $limit) {
		$err = "";
		
		
		
		$translator = new Zend_Translate ( 'array', APPLICATION_PATH . "/../library/Zen/Errors.php" );
		$res = array ('errors' => $err );
		
		/*Современные браузеры*/
		if (isset ( $_GET ['qqfile'] )) {
			$name = trim ( $_GET ['qqfile'] );
			$out = array ();
			preg_match ( '/\S+\.(\S+)$/', $name, $out );
			$name_short = preg_replace ( '/\\.\\D*$/ui', '', $name );
			$res['type'] = mb_strtolower($out [1],'UTF-8');
			
			$input = fopen ( "php://input", "r" );
			$newname='tmp_'.md5($name).'.'.$res['type'];
			$res['name']=$newname;
			$fp = @fopen ( $path . $newname, "w" );
			if (! $fp) {
				$res ['errors'] ['create_error'] = 'Не удалось создать файл по адресу ' . $path . $name;
			}
			
			while ( $data = fread ( $input, 1024 ) ) {
				fwrite ( $fp, $data );
			}
			fclose ( $fp );
			fclose ( $input );
			
			if (!function_exists('apache_request_headers')) {
			
				$size=$_SERVER['CONTENT_LENGTH'];
			}else{
				$headers = apache_request_headers ();
				$size = $headers ['Content-Length'];
			}
			if ($size == 0) {
				$res ['errors'] ['nofile_upload'] = 'Файл не был загружен';
			
			}
			
			if ($size > $limit) {
				$res ['errors'] ['nofile_upload'] = 'Файл слишком большой';
			
			}
			if (! in_array ( $res['type'], $extensions )) {
				$res ['errors'] ['nofile_upload'] = 'Неверное расширение файла';
			}
			
			
			return $res;
			
		/*Старые браузеры*/
		} else {
			$adapter = new Zend_File_Transfer_Adapter_Http ();
			
			$adapter->setTranslator ( $translator );
			$adapter->setDestination ( $path );
			$adapter->addValidator ( 'Size', false, $limit );
			$adapter->addValidator ( 'ImageSize', false, array ('minwidth' => 10, 'minheight' => 10 ) );
			$adapter->addValidator ( 'Extension', false, implode ( ',', $extensions ) );
			$name = $adapter->getFileName ( null, false );
			$res['name']=$name;
			$out = array ();
			preg_match ( '/\S+\.(\S+)$/', $name, $out );
			$name_short = preg_replace ( '/\\.\\D*$/ui', '', $name );
			$res['type'] = mb_strtolower($out [1],'UTF-8');
			if (! $adapter->isValid ()) {
				$messages = $adapter->getMessages ();
				$res ['errors'] = $messages;
			} else {
				if (! $adapter->receive ()) {
					$messages = $adapter->getMessages ();
					$res ['errors'] = $messages;
				} 
			}
			return $res;
		}
	
	}	
	
}

?>